//
//  XLFoundViewController.m
//  XiangLove
//
//  Created by feng song on 2018/3/14.
//  Copyright © 2018年 BAOMIHUA.COM. All rights reserved.
//

#import "XLFoundViewController.h"
 #import "CallIncomingListenner.h"
#import <VTMagic.h>
#import "XLNewHomeViewController.h"
#import "XLCharmViewController.h"
#import "XLContributionViewController.h"
#import "XLArchorLeadView.h"
#import "XLAnchorCommitInforVC.h"
#import "XLHostSideTuijianVC.h"
#import "XLHostSideAliveVC.h"
#import "XLHostSideNewPersonVC.h"
#import "XLNearbyViewController.h"
#import "XLUserSideNewPersonVC.h"
#import "XLHTTPSessionManager.h"
#import <ReactiveCocoa.h>
#import "XLTabBarController.h"
#import "XLNewUserBagView.h"
#import "XLNewUserModel.h"
#import <IQKeyboardManager/IQKeyboardManager.h>
#import "XLReprotUserVC.h"
#import "XLSearchViewController.h"
#import "XLCommitGender.h"
#import "XLCommitSetSirView.h"
#import "XLCommitDataController.h"
#import "TurnCircleTableView.h"
#import "XLHomeViewModel.h"

@interface XLFoundViewController ()<VTMagicViewDelegate,VTMagicViewDataSource,XLNewUserBagViewDelegate,XLCommitGenderDelegate>{
    UIView *baseBackview;
    UIButton *SelectButton;
}

@property (nonatomic, strong) VTMagicController *magicController;
@property (nonatomic, strong) NSArray           *menuArray;
@property (nonatomic, strong) NSArray           *menuConfigArray;
@property (nonatomic, assign) NSUInteger         currentShowingPageId;
@property (nonatomic, strong) NSMutableArray           *gifArray;
@property (nonatomic, strong) XLHomeViewModel * viewModel;


//礼包界面
@property (nonatomic, strong) XLNewUserBagView * userNewBagView;

//设置新手浮标
@property (nonatomic, strong) UIImageView *  fuBiaoImage;

//设置免费次数
@property (nonatomic, strong) UILabel *  timesLbl;

//数据源
@property (nonatomic, strong) XLNewUserModel *  UserNewModel;


/**
 承载新用户弹窗填写信息
 */
@property (nonatomic, strong) UIWindow *  window;

//选择性别
@property (nonatomic, strong) XLCommitGender *  commitGender;

//自动设置男性信息
@property (nonatomic, strong) XLCommitSetSirView *  commitSetInfo;

//领豆按钮
@property (nonatomic, strong) UIView * awardView;

@end

@implementation XLFoundViewController
{
    //是否请求过了新手大礼包
    BOOL requestYES;
    
    //弹窗背景设置
    UIView *bgView;
}


- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleDefault;
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    [UserDefaults setObject:@"0" forKey:@"tabBarSelectedIndex"];
    [UserDefaults synchronize];
//    XLTabBarController *tabVC = (XLTabBarController *)self.tabBarController;
//    [tabVC.launchAnimation play];
    [[IQKeyboardManager sharedManager] setShouldResignOnTouchOutside:YES];
    
    //是否设置过性别信息等 如果设置过了 来到首页显示新手礼包
    BOOL isShowBag = [UserDefaults boolForKey:@"isNewBag"];
    
    /**
     判断是否是新用户
     */
    BOOL isNewUser = [[XLAccountManager shareInstance].model.IsNewUser boolValue];

    //符合条件 请求礼包信息：新人 设置性别信息完毕
    if (isNewUser == YES && isShowBag) {
        [self requestSourceTimes];
    }
    
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:YES];
    
}
-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:YES];
    
}
//iOS 判断是否允许消息通知
- (BOOL)openThePushNotification{
    if (SYSTEM_VERSION_GREATER_THAN(@"8.0")) {//IOS8写的宏
        if ([[UIApplication sharedApplication] currentUserNotificationSettings].types  == UIUserNotificationTypeNone) {
            return NO;
        }else{
            
            return YES;
        }
    }else{ // ios7
        if ([[UIApplication sharedApplication] enabledRemoteNotificationTypes]  == UIUserNotificationTypeNone) {
            return NO;
        }else{
            
            return YES;
        }
    }
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    BOOL isReciveNoti = [self openThePushNotification];
    if (isReciveNoti == NO && [[[XLAccountManager shareInstance] model].IsAnchor isEqualToString:@"1"]) {
        UIAlertController * alert = [UIAlertController
                                     alertControllerWithTitle:@"温馨提示"
                                     message:@"打开通知权限才能实时接收视频邀请哦"
                                     preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction * defaultAction = [UIAlertAction actionWithTitle:@"开启" style:UIAlertActionStyleDefault
                                                              handler:^(UIAlertAction * action) {
                                                                  [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];

        }];
        
        [alert addAction:defaultAction];
        [self presentViewController:alert animated:YES completion:nil];
    }
    
    self.menuConfigArray = [self getCommonMenuConfig];
    [self generateTestData];
    self.fd_prefersNavigationBarHidden = YES;
    [self initMagicView];
    _gifArray = [[NSMutableArray alloc]init];
    [self getFlowerList];
    
    // QDXStart!
    SelectButton = [UIButton buttonWithType:UIButtonTypeCustom];
    SelectButton.hidden = YES;
//    SelectButton.frame = CGRectMake(10, 20, 50, 40);
//    if (IS_IPHONE_X) {
//        SelectButton.frame = CGRectMake(10, 40, 40, 40);
//    }
    SelectButton.frame = CGRectMake(20, 30, 24, 24);
    if (IS_IPHONE_X) {
        SelectButton.frame = CGRectMake(20, 30, 24, 24);
    }
    [SelectButton addTarget:self action:@selector(changeSelect) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:SelectButton];
//    [SelectButton setImage:[UIImage imageNamed:@"common_icon_select_n"] forState:UIControlStateNormal];
    [SelectButton setImage:[UIImage imageNamed:@"common_icon_select_new_n"] forState:UIControlStateNormal];
    
    UIButton *searchButton = [UIButton buttonWithType:UIButtonTypeCustom];
//    searchButton.frame = CGRectMake(ScreenWidth - 60, 20, 50, 40);
//    if (IS_IPHONE_X) {
//        searchButton.frame = CGRectMake(ScreenWidth - 60, 40, 40, 40);
//    }
    searchButton.frame = CGRectMake(ScreenWidth - 44, 30, 24, 24);
    if (IS_IPHONE_X) {
        searchButton.frame = CGRectMake(ScreenWidth - 44, 50, 24, 24);
    }
    [searchButton addTarget:self action:@selector(searchVC) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:searchButton];
    // QDXStart!
//    [searchButton setImage:[UIImage imageNamed:@"common_nav_but_sousuo_n"] forState:UIControlStateNormal];
    [searchButton setImage:[UIImage imageNamed:@"common_nav_but_sousuo_new_n"] forState:UIControlStateNormal];
    // QDXEnd!

    /**
     新用户设置信息
     */
    BOOL isCommit = [[[XLAccountManager shareInstance] model].Status isEqualToString:@"2"];
    
    // 否弹窗显示： Status != 2 & isNewUser == YES & sex == 1
    //或者 BoundSource == 2 & isNewUser == YES & sex == 1
    BOOL isWXCommit = ([[XLAccountManager shareInstance] model].BoundSource == 2) && [[[XLAccountManager shareInstance] model].IsNewUser isEqualToString:@"1"] && [[XLAccountManager shareInstance] model].Sex == 1;
    
    //默认不弹窗礼包 等待性别信息设置完毕之后弹窗
    [UserDefaults setBool:NO forKey:@"isNewBag"];
    
    if (isCommit) {
        [self commitNewUserInfo];
    }else if (isWXCommit){
        [self pushToCommitVc:[[XLAccountManager shareInstance] model].Sex];
    }
    [self.view addSubview:self.awardView];
    [self getloginfortun];
    
}

-(void)getloginfortun
{
    [[[XLHTTPSessionManager sharedManager]XLV2GET:@"/api/v2/UserInfo/LoginWheelFortun" parameters:@{@"userId":[[XLAccountManager shareInstance]model].Id} resultClass:nil] subscribeNext:^(id x) {
        NSArray * data = (NSArray *)x;
        
    } error:^(NSError *error) {
        NSLog(@"%@", error);
    }];
}

- (void)searchVC{
    XLSearchViewController *vc = [[XLSearchViewController alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
}
//筛选窗
- (void)changeSelect{//改变筛选条件
    baseBackview = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
    baseBackview.backgroundColor = kClearColor;
    UITapGestureRecognizer *TAP = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(dismissView)];
    [baseBackview addGestureRecognizer:TAP];
    [self.view addSubview:baseBackview];

    UIView *selectBackview = [[UIView alloc]initWithFrame:CGRectMake(10, 74, 180, 210)];
    selectBackview.backgroundColor = RGB_HEX(0xFBFBFB);
    selectBackview.layer.cornerRadius = 5;
    [baseBackview addSubview:selectBackview];
    UIButton *selectButton1 = [UIButton buttonWithType:UIButtonTypeCustom];
    selectButton1.frame = CGRectMake(0, 0, 180, 70);selectButton1.tag = 101;
    [selectButton1 addTarget:self action:@selector(clickSelectButton:) forControlEvents:UIControlEventTouchUpInside];
    [selectBackview addSubview:selectButton1];
    [selectButton1 setTitle:@"女生" forState:UIControlStateNormal];
    [selectButton1 setImage:[UIImage imageNamed:@"common_icon_girls_pink_n"] forState:UIControlStateNormal];
    UIButton *selectButton2 = [UIButton buttonWithType:UIButtonTypeCustom];
    selectButton2.frame = CGRectMake(0, 70, 180, 70);
    [selectButton2 addTarget:self action:@selector(clickSelectButton:) forControlEvents:UIControlEventTouchUpInside];
    [selectBackview addSubview:selectButton2];selectButton2.tag = 102;
    [selectButton2 setTitle:@"男生" forState:UIControlStateNormal];
    [selectButton2 setImage:[UIImage imageNamed:@"common_icon_boy_blue_n"] forState:UIControlStateNormal];
    UIButton *selectButton3 = [UIButton buttonWithType:UIButtonTypeCustom];
    selectButton3.frame = CGRectMake(0, 140, 180, 70);
    [selectButton3 addTarget:self action:@selector(clickSelectButton:) forControlEvents:UIControlEventTouchUpInside];
    [selectBackview addSubview:selectButton3];selectButton3.tag = 103;
    [selectButton3 setTitle:@"全部" forState:UIControlStateNormal];
    [selectButton3 setImage:[UIImage imageNamed:@"common_icon_bg_n"] forState:UIControlStateNormal];
    [selectButton1 setTitleColor:kDarkGrayColor forState:UIControlStateNormal];
    [selectButton2 setTitleColor:kDarkGrayColor forState:UIControlStateNormal];
    [selectButton3 setTitleColor:kDarkGrayColor forState:UIControlStateNormal];
}
- (void)clickSelectButton:(UIButton *)sender{
    NSDictionary *dict = @{@"key":@(sender.tag)};
    [[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:@"changeSelectInfor" object:nil userInfo:dict]];
    [UIView animateWithDuration:0.8 animations:^{
        baseBackview.alpha = 0;
    } completion:^(BOOL finished) {
        [baseBackview removeFromSuperview];
    }];
}
- (void)dismissView{
    [UIView animateWithDuration:0.8 animations:^{
        baseBackview.alpha = 0;
    } completion:^(BOOL finished) {
        [baseBackview removeFromSuperview];
    }];
}
/**
 新用户资料整理
 */
- (void)commitNewUserInfo
{
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.windowLevel = UIWindowLevelAlert+1;
    [self.window makeKeyAndVisible];
    self.window.backgroundColor = [UIColor clearColor];
    
    bgView = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    bgView.backgroundColor = RGBA(0, 0, 0, 0.5);
    [self.window addSubview:bgView];
    
    self.commitGender = [[XLCommitGender alloc] initWithFrame:CGRectMake(0, 0, 270, 237)];
    CGPoint center = bgView.center;
    self.commitGender .center = CGPointMake(center.x, center.y);
    
    self.commitGender .delegate = self;
    
    [bgView addSubview:self.commitGender ];
}

- (void)commitSetInfoView
{
    NSString *avatarUrl = [[XLAccountManager shareInstance] model].HeadImg;
    
//    NSInteger temp = [[XLAccountManager shareInstance] model].Sex;
    
    NSString *sex;
    if ([[XLAccountManager shareInstance] model].Sex == 0) {
        sex = @"男";
    }else{
        //目前不可能是女，只有男才跳过来
        sex = @"女";
    }
    
    NSString *age = [NSString stringWithFormat:@"%ld",[XLAccountManager shareInstance].model.Age];
    
    
    self.commitSetInfo = [[XLCommitSetSirView alloc] initWithFrame:CGRectMake(0, 0, 270, 265)];
    CGPoint center = bgView.center;
    self.commitSetInfo .center = CGPointMake(center.x, center.y);
    [self.commitSetInfo.saveSucessBt addTarget:self action:@selector(changeSetToCommitView:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.commitSetInfo.deleteButton addTarget:self action:@selector(deleteCommitSetInfoView:) forControlEvents:(UIControlEventTouchUpInside)];
    
    [self.commitSetInfo.avatarView sd_setImageWithURL:[NSURL URLWithString:avatarUrl]];
    self.commitSetInfo.nickName.attributedText = [self.commitSetInfo setNickNameAttributeWithString:[XLAccountManager shareInstance].model.NickName];
    self.commitSetInfo.genderLbl.attributedText = [self.commitSetInfo setGenderString:sex];
    self.commitSetInfo.ageLbl.attributedText = [self.commitSetInfo setAgeString:age];
    
    
    [bgView addSubview:self.commitSetInfo];
}

//选择 0男 1女 代理
- (void)commitGenderSelectIndex:(NSInteger)index
{
    if (index == 0) {
        //男 进入自动设置
        
        [UIView transitionWithView:self.view duration:0.3 options:UIViewAnimationOptionTransitionCrossDissolve animations:^{
            
            self.commitGender.alpha = 0;
            
        } completion:^(BOOL finished) {
            
            //创建设置信息界面
            [self commitSetInfoView];
            
            //删除选择性别界面
            [self.commitGender removeFromSuperview];
        }];
        
    }else{
        //女 编辑页
        [self pushToCommitVc:1];
    }
}

//如果是男 设置好之后 进入编辑页
- (void)changeSetToCommitView:(UIButton *)sender
{
    [self pushToCommitVc:0];
}

- (void)pushToCommitVc:(NSInteger)index
{
    //弹窗完毕 可以提示礼包信息
    [UserDefaults setBool:YES forKey:@"isNewBag"];
    
    [self.window resignKeyWindow];
    self.window = nil;
    
    XLCommitDataController *vc = [[XLCommitDataController alloc] init];
    vc.userId = [XLAccountManager shareInstance].model.Id;
    
    if (index == 1) {
        vc.isCommit = YES;
    }else{
        vc.isCommit = NO;
    }
    
    
    
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)deleteCommitSetInfoView:(UIButton *)sender
{
    //弹窗完毕 可以提示礼包信息
    [UserDefaults setBool:YES forKey:@"isNewBag"];
    
    [self.window resignKeyWindow];
    self.window = nil;
    
    /**
     判断是否是新用户
     */
    BOOL isNewUser = [[XLAccountManager shareInstance].model.IsNewUser boolValue];
    
    //符合条件 请求礼包信息：新人 设置性别信息完毕
    if (isNewUser ==YES) {
        [self requestSourceTimes];
    }
}








/**
 获取免费次数
 */
- (void)requestSourceTimes
{
    //设置不再弹窗
    [UserDefaults setBool:NO forKey:@"isNewBag"];
    //视频体验卡请求信息
    [[[XLHTTPSessionManager sharedManager] XLV2GET:@"/Api/v2/GiftPackag/GetGiftPackag" parameters:@{@"name":@"newuser"} resultClass:[XLUserInfoModel class]] subscribeNext:^(id x) {
        
        //请求成功 说明有礼包
        self.UserNewModel = x;
        
        //展示礼包信息
        [self layOutUserGiftBag];
        
    } error:^(NSError *error) {
        //请求不成功 不需要展示礼包
        NSLog(@"请求新手礼包：%@",error.localizedDescription);
    }];
    
}


/**
 用户礼包界面
 */
- (void)layOutUserGiftBag
{
    
    //设置背景容器
    
    self.userNewBagView = [[XLNewUserBagView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
    
    self.userNewBagView.backgroundColor =  [UIColor colorWithRed:0/255.0 green:0/255.0 blue:0/255.0 alpha:0.5];
    self.userNewBagView.delegate = self;
    
    
}

//设置新手浮标
- (void)setFuBiaoView
{
    [self.view addSubview:self.fuBiaoImage];
    
    [self.fuBiaoImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view.mas_right);
        make.bottom.equalTo(self.view.mas_bottom).offset(-5);
        make.width.equalTo(@70);
        make.height.equalTo(@70);
    }];
    
    self.timesLbl.text = @"免费视频\n剩3次";
    
    [self.fuBiaoImage addSubview:self.timesLbl];
    
    [self.timesLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(50, 28));
        make.center.equalTo(self.fuBiaoImage);
    }];
}

-(void)initMagicView
{
    _magicController = [[VTMagicController alloc] init];
//    _magicController.magicView.scro
    _magicController.view.translatesAutoresizingMaskIntoConstraints = NO;
    _magicController.magicView.navigationColor = RGB_HEX(0xffffff);
    // QDXStart!
//    _magicController.magicView.itemScale = 1.143;
    _magicController.magicView.itemScale = 1.005;
//    _magicController.magicView.sliderColor = HEXCOLOR(0x000000);//滑动条
    _magicController.magicView.sliderColor = HEXCOLOR(0x333333);//滑动条
    // QDXEnd!
    _magicController.magicView.sliderHeight = 2;
    _magicController.magicView.itemSpacing = 27;
    _magicController.magicView.displayCentered = YES;
    _magicController.magicView.switchStyle = VTSwitchStyleDefault;
    _magicController.magicView.layoutStyle = VTLayoutStyleCenter;
    if (IS_IPHONE_X) {
        _magicController.magicView.navigationHeight = 88.f;
    }else{
        _magicController.magicView.navigationHeight = 64.f;
    }
    _magicController.magicView.navigationInset = UIEdgeInsetsMake(10, 0, 0, 0);
    _magicController.magicView.againstStatusBar = NO;
    _magicController.magicView.sliderExtension = 2;
    _magicController.magicView.sliderOffset = -5;
    _magicController.magicView.dataSource = self;
    _magicController.magicView.delegate = self;
    _magicController.magicView.separatorColor = [UIColor groupTableViewBackgroundColor];
    [self addChildViewController:_magicController];
    [self.view addSubview:_magicController.view];
    [_magicController.magicView reloadData];
    [_magicController.magicView switchToPage:1 animated:NO];
    
}

#pragma mark    -   -   - XLNewUserBagDelegate -    -   -

//删除界面 不领取
- (void)xlNewUserBagDeleteNewUserBag:(UIButton *)sender
{
//    [self setFuBiaoView];
//    self.timesLbl.text = [NSString stringWithFormat:@"免费视频\n剩%@次",K_DEFULT(self.UserNewModel.FreeCountString)];
//    self.fuBiaoImage.hidden = NO;
}

//领取礼包
- (void)xlNewUserBagClickReceive:(UIButton *)sender
{
//    [self setFuBiaoView];
//    self.timesLbl.text = [NSString stringWithFormat:@"免费视频\n剩%@次",K_DEFULT(self.UserNewModel.FreeCountString)];
//    self.fuBiaoImage.hidden = NO;
}


#pragma mark - DataDelegate
- (NSArray<NSString *> *)menuTitlesForMagicView:(VTMagicView *)magicView {
    return _menuArray;
}

- (UIButton *)magicView:(VTMagicView *)magicView menuItemAtIndex:(NSUInteger)itemIndex {
    static NSString *itemIdentifier = @"itemIdentifier";
    UIButton *menuItem = [magicView dequeueReusableItemWithIdentifier:itemIdentifier];
    if (!menuItem) {
        menuItem = [UIButton buttonWithType:UIButtonTypeCustom];
        
        // QDXStart!
//        [menuItem setTitleColor:HEXCOLOR(0x6A6978) forState:UIControlStateNormal];
//        [menuItem setTitleColor:HEXCOLOR(0x000000) forState:UIControlStateSelected];
        
        [menuItem setTitleColor:HEXCOLOR(0x333333) forState:UIControlStateNormal];
        [menuItem setTitleColor:HEXCOLOR(0x333333) forState:UIControlStateSelected];
        // QDXEnd!
        
        menuItem.titleLabel.font = [UIFont systemFontOfSize:17.f];
    }
    return menuItem;
}
- (UIViewController *)magicView:(VTMagicView *)magicView viewControllerAtPage:(NSUInteger)pageIndex {
    NSString *title = self.menuArray[pageIndex];
    if ([title isEqualToString:@"推荐"]) {
        if ([[[XLAccountManager shareInstance] model].IsAnchor isEqualToString:@"1"]) {//是主播
            XLHostSideTuijianVC *vc = [magicView dequeueReusablePageWithIdentifier:F(@"%@%zd", NSStringFromClass([XLHostSideTuijianVC class]), pageIndex)];
            if (vc == nil) {
                vc = [[XLHostSideTuijianVC alloc] init];
            }
            kWeakSelf(self);
            vc.slideDistanceBlock = ^(BOOL isSlideDown) {
                [weakself awardViewIsShow:!isSlideDown];
            };
            return vc;
        }
        XLNewHomeViewController *vc = [magicView dequeueReusablePageWithIdentifier:F(@"%@%zd", NSStringFromClass([XLNewHomeViewController class]), pageIndex)];
        if (vc == nil) {
            vc = [[XLNewHomeViewController alloc] init];
        }
        kWeakSelf(self);
        vc.slideDistanceBlock = ^(BOOL isSlideDown) {
            [weakself awardViewIsShow:!isSlideDown];
        };
        return vc;
    }else if ([title isEqualToString:@"附近"]) {
        XLNearbyViewController *vc = [magicView dequeueReusablePageWithIdentifier:F(@"%@%zd", NSStringFromClass([XLNearbyViewController class]), pageIndex)];
        if (vc == nil) {
            vc = [[XLNearbyViewController alloc] init];
            
        }
        kWeakSelf(self);
        vc.slideDistanceBlock = ^(BOOL isSlideDown) {
            [weakself awardViewIsShow:!isSlideDown];
        };
        return vc;
    }
    else{
        if ([[[XLAccountManager shareInstance] model].IsAnchor isEqualToString:@"1"]) {//是主播  old
            XLHostSideAliveVC *vc = [magicView dequeueReusablePageWithIdentifier:F(@"%@%zd", NSStringFromClass([XLHostSideAliveVC class]), pageIndex)];
            if (vc == nil) {
                vc = [[XLHostSideAliveVC alloc] init];
            }
            kWeakSelf(self);
            vc.slideDistanceBlock = ^(BOOL isSlideDown) {
                [weakself awardViewIsShow:!isSlideDown];
            };
            return vc;
        }
        XLUserSideNewPersonVC *vc = [magicView dequeueReusablePageWithIdentifier:F(@"%@%zd", NSStringFromClass([XLUserSideNewPersonVC class]), pageIndex)];
        if (vc == nil) {
            vc = [[XLUserSideNewPersonVC alloc] init];
        }
        kWeakSelf(self);
        vc.slideDistanceBlock = ^(BOOL isSlideDown) {
            [weakself awardViewIsShow:!isSlideDown];
        };
        return vc;
    }
}

-(void)awardViewIsShow:(BOOL)isShow
{
    if(isShow)
    {
        [UIView animateWithDuration:0.2 animations:^{
            [self.awardView setHx_x:0];
        }];
    }else
    {
        [UIView animateWithDuration:0.2 animations:^{
            [self.awardView setHx_x:-18];
        }];
    }
}
                                      

- (void)magicView:(VTMagicView *)magicView viewDidAppear:(__kindof UIViewController *)viewController atPage:(NSUInteger)pageIndex {
    if (pageIndex == 0) {
        SelectButton.hidden = NO;
    }else{
        SelectButton.hidden = YES;
    }
    self.currentShowingPageId = pageIndex;
    NSLog(@"%zd", self.currentShowingPageId);
}

- (void)generateTestData {
    NSMutableArray *menu = [NSMutableArray array];
    for (NSDictionary *dic in self.menuConfigArray) {
        [menu addObject:dic[@"title"]];
    }
    _menuArray = menu.copy;
}

- (NSArray *)getCommonMenuConfig
{
    NSString * guideTitle = @"新人";
    if([[[XLAccountManager shareInstance] model].IsAnchor isEqualToString:@"1"])
    {
        guideTitle = @"活跃";
    }
    
    NSArray *commnMenu;
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:XiangLove_IsSH] boolValue]) {//
        commnMenu = @[
                      @{
                          @"title": @"附近",
                          @"recommend_tagid": @"305",
                          @"focus_tagid": @"1650",
                          @"show_style": @"0",
                          @"bmh_stat": @"index",
                          @"channel_image": @"channel_recommend.png",
                          @"type_code" : @"square_follow"
                          },
                      
                      @{
                          @"title": @"推荐",
                          @"recommend_tagid": @"306",
                          @"focus_tagid": @"1750",
                          @"show_style": @"0",
                          @"bmh_stat": @"zixunindex",
                          @"channel_image": @"channel_hot.png",
                          @"type_code" : @"square_new"
                          },
                      ];
    }else{
        commnMenu = @[
                      @{
                          @"title": @"附近",
                          @"recommend_tagid": @"305",
                          @"focus_tagid": @"1650",
                          @"show_style": @"0",
                          @"bmh_stat": @"index",
                          @"channel_image": @"channel_recommend.png",
                          @"type_code" : @"square_follow"
                          },
                      
                      @{
                          @"title": @"推荐",
                          @"recommend_tagid": @"306",
                          @"focus_tagid": @"1750",
                          @"show_style": @"0",
                          @"bmh_stat": @"zixunindex",
                          @"channel_image": @"channel_hot.png",
                          @"type_code" : @"square_new"
                          },
                      @{
                          @"title": guideTitle,
                          @"recommend_tagid": @"307",
                          @"focus_tagid": @"1749",
                          @"show_style": @"0",
                          @"bmh_stat": @"yuleindex",
                          @"channel_image": @"channel_amuse.png",
                          @"type_code" : @"square_original"
                          },
                      ];
    }
    
    
    return commnMenu;
}

#pragma mark *************获取礼物列表
-(void)getFlowerList
{
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@"5", @"type",nil];
    [[[XLHTTPSessionManager sharedManager] XLV2GET:@"/Api/V2/Gift/GetGiftList" parameters:dic resultClass:nil] subscribeNext:^(id x) {
        
        for (NSDictionary *dic in x) {
            if (![dic[@"MoveImg"]isKindOfClass:[NSNull class]]){
                [_gifArray addObject:dic[@"MoveImg"]];
            }
        }
        
        [self saveImageDataToFile];
    } error:^(NSError *error) {
        
    }];
    
}
- (void)saveImageDataToFile{
    
    dispatch_queue_t queue2 = dispatch_queue_create("queue", NULL);
    NSArray *tempArray = [[NSUserDefaults standardUserDefaults]objectForKey:@"fileGiftArray"];
    NSMutableArray *PathArray = [[NSMutableArray alloc]initWithArray:tempArray];
    dispatch_async(queue2, ^{
        for (NSString *urlString in _gifArray) {
            if ([PathArray containsObject:urlString]) {
                //已缓存
            }else{
                //获取imgedata
                NSError * error2;
                NSData * data = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlString] options:NSDataReadingMappedIfSafe error:&error2];
                // 写入本地沙盒目录
                NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
                NSString *fileName = [[urlString componentsSeparatedByString:@"/"]lastObject];
                NSString *imageFilePath = [path stringByAppendingPathComponent:fileName];
                
                BOOL success =  [data writeToFile:imageFilePath atomically:NO];
                
                if (success){
                    [PathArray addObject:urlString];
                    NSLog(@"写入本地成功%@",imageFilePath);
                }else{
                    NSLog(@"失败%@",imageFilePath);
                }
            }
        }
        [[NSUserDefaults standardUserDefaults]setObject:PathArray forKey:@"fileGiftArray"];
        NSLog(@"子线程");
    });
    NSLog(@"主线程");
}


#pragma mark    ---懒加载---

- (UILabel *)timesLbl
{
    if (!_timesLbl) {
        self.timesLbl = [[UILabel alloc] init];
        
        self.timesLbl.textAlignment = NSTextAlignmentCenter;
        
        self.timesLbl.font = [UIFont systemFontOfSize:10];
        
        self.timesLbl.numberOfLines = 2;
        
        self.timesLbl.textColor = [UIColor whiteColor];
        
    }
    
    return _timesLbl;
}

- (UIImageView *)fuBiaoImage
{
    if (!_fuBiaoImage) {
        self.fuBiaoImage = [[UIImageView alloc] init];
        
        self.fuBiaoImage.image = [UIImage imageNamed:@"common_bg_libao_fubiao"];
    }
    return _fuBiaoImage;
}

-(UIView *)awardView
{
    if(_awardView == nil)
    {
        _awardView = [[UIView alloc]initWithFrame:CGRectMake(-18, KScreenHeight - (49 + kViewToBottom + 7 + 58), 47, 58)];
        UIImageView * bottomImage = [[UIImageView alloc]init];
        bottomImage.image = IMAGE_NAMED(@"lingdou_hongbao_2");
        [_awardView addSubview:bottomImage];
        
        [bottomImage mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_equalTo(_awardView).insets(UIEdgeInsetsMake(2, 0, 2, 0));
        }];
        
        UIImageView * topImage = [[UIImageView alloc]init];
        topImage.image = IMAGE_NAMED(@"lingdou_hongbao_3");
        [_awardView addSubview:topImage];
        if(![[[XLAccountManager shareInstance] model].IsAnchor isEqualToString:@"1"])
        {
            _awardView.hidden = NO;
        }else
        {
            _awardView.hidden = YES;
        }
        if ([[[NSUserDefaults standardUserDefaults] objectForKey:XiangLove_IsSH] boolValue]) {//
            _awardView.hidden = YES;
        }
        [topImage mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_awardView.mas_left).offset(0);
            make.top.equalTo(_awardView.mas_top).offset(0);
            make.bottom.equalTo(_awardView.mas_bottom).offset(0);
            make.width.equalTo(@28);
        }];
        
        UIButton * btn = [[UIButton alloc]init];
        [_awardView addSubview:btn];
        [btn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(_awardView);
        }];
        kWeakSelf(self);
        [btn addTapBlock:^(UIButton *btn) {
            [weakself didClickAwardBtn];
        }];
    }
    return _awardView;
}

#pragma mark -- 点击大转盘
-(void)didClickAwardBtn
{
    [self.viewModel getWheelFortunInfoComplete:^(XLWheelFortunModel *model) {
        TurnCircleTableView * turnCicleView = [[TurnCircleTableView alloc] initWithFrame:[UIScreen mainScreen].bounds AndModel:model];
        [kAppWindow addSubview:turnCicleView];
    }];
}

-(XLHomeViewModel *)viewModel
{
    if(_viewModel == nil)
    {
        _viewModel = [[XLHomeViewModel alloc]init];
    }
    return _viewModel;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
